import json, time
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.views import View
from homes.models import Area, House, HouseImage, Facility
from django.core.paginator import Paginator, EmptyPage
from fdfs_client.client import Fdfs_client
from orders.models import Order
import logging
# Create your views here.


logger = logging.getLogger('django')

'''城区列表'''
class AreaHouseView(View):
    '''城区列表'''
    def get(self,request):
        try:
           areas = Area.objects.all()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errmsg':'未找到城区',
                                      'errno':4002})

        area_list = []
        for area in areas:
            area_list.append({'aid':area.id,
                              'aname':area.name})

        return JsonResponse({'errmsg':'获取成功',
                                  'errno':0,
                                  'data':area_list})


'''发布房源'''
class ShowHouseView(View):

    def get(self,request):

        aid = request.GET.get('aid')#城区
        sd = request.GET.get('sd')#开始时间
        ed = request.GET.get('ed')#结束时间
        sk = request.GET.get('sk')#排序方式
        p = request.GET.get('p')#页数


        # 检验参数
        if not all([aid, sd, ed, sk, p]):
            return JsonResponse({'errno': 4130, 'errmsg': "缺少必传参数"})

        try:
            start_date = None
            end_date = None
            if sd:
                start_date = time.strptime(sd,"%Y-%m-%d")
                end_date = time.strptime(ed, '%Y-%m-%d')
                # 更改时间数据类型
                start_date = int(time.mktime(start_date))
                end_date = int(time.mktime(end_date))


            if start_date and end_date:
                assert start_date <= end_date

        except Exception as e:
            return JsonResponse({'errmsg':'日期参数错误','errno':4130,})


        if not p:
            p = 1
        else:
            try:
                p = int(p)
            except Exception as e:
                return JsonResponse({'errmsg':'参数page错误','errno':4130,})

        try:
            # 根据area_id划分城区
            area = Area.objects.get(id=aid)
            hs = House.objects.filter(area=area) # 获取在某地区的房源
        except Exception as e:
            return JsonResponse({'errmsg':'获取房源失败','errno':4002,})

        # 没有获取到房源
        if not hs:
            return JsonResponse({'errmsg': '获取房源失败', 'errno': 4002, })

        hs_id_list = []
        for house in hs:
            hs_id_list.append(house.id)

        #订单列表
        order_list = []

        try:
            order = Order.objects.filter(house_id__in=hs_id_list)
            if order:
                order_list.append(order)
        except Exception as e:
            return  JsonResponse({'errmsg': '获取房源失败', 'errno': 4002, })


        # 获取房源订单进行时间对比,筛选出该时间段未出租的房源
        house_id_list = []
        for orders in order_list:

            for order in orders:

                # 更换时间数据的类型才能比较
                order.begin_date = int(time.mktime(time.strptime(str(order.begin_date)[:10], "%Y-%m-%d")))
                order.end_date = int(time.mktime(time.strptime(str(order.end_date)[:10], "%Y-%m-%d")))


                # 比较时间,筛选出该时间段未出租的房源
                if order.begin_date >= end_date:
                    house_id_list.append(order.user_id)
                elif order.end_date <= start_date:
                    house_id_list.append(order.user_id)

        try:
            if sk == 'price-des':
                houses = House.objects.filter(area=area,id__in=hs_id_list).order_by('-price')
            elif sk =='price-inc':
                houses = House.objects.filter(area=area,id__in=hs_id_list).order_by('price')
            else:
                houses = House.objects.filter(area=area,id__in=hs_id_list).order_by('order_count')

        except Exception as e:
            return JsonResponse({'errmsg':'获取房源失败','errno':4002,})


        houses = House.objects.filter(area_id=area.id)

        # # 分页
        pg = Paginator(houses, 2)
        try:
            pg_houses = pg.page(p)
        except EmptyPage:
            return JsonResponse({'errmsg':'该页面没有数据','errno':4002,})
        total_page = pg.num_pages

        house_list = []
        for house in houses:
            house_list.append({'house_id':house.id,
                               'order_count':house.order_count,
                               'title':house.title,
                               'ctime':house.create_time.strftime("%Y-%m-%d"),
                               'price':house.price,
                               'area_name':house.area.name,
                               'address':house.address,
                               'room_count':house.room_count,
                               'img_url': settings.FDFS_BASE_URL + house.index_image_url,
                               # 取出ImageField文件的方式
                               'user_avatar':house.user.avatar.url})

        data = {'houses':house_list,
                'total_page':total_page}

        return JsonResponse({'errno':0,'data':data,'errmsg':'获取成功'})

    def post(self,request):
        # 判断用户是否登录
        if not request.user.is_authenticated():
            return JsonResponse({'errno': '1', 'errmsg': '未登录'})

        dict = json.loads(request.body.decode())
        title = dict.get('title')
        price = dict.get('price')
        area_id = dict.get('area_id')
        address = dict.get('address')
        room_count = dict.get('room_count')
        acreage = dict.get('acreage')
        unit = dict.get('unit')
        capacity = dict.get('capacity')
        beds = dict.get('beds')
        deposit = dict.get('deposit')
        min_days = dict.get('min_days')
        max_days = dict.get('max_days')
        facility_id_list = dict.get('facility')

        if not all([title, price, area_id, address, room_count,
                    acreage, unit, capacity, beds, deposit,
                    min_days, max_days, facility_id_list]):
            return JsonResponse({'errmsg': '参数缺少',
                                      'errno': 4103, })

        if facility_id_list:
            # 表示用户勾选了房屋设施
            # 过滤用户传送的不合理的设施id
            try:
                facility_list = Facility.objects.filter(id__in=(facility_id_list)).all()
                # 保存房源信息
                area = Area.objects.get(id=area_id)

                house = House.objects.create(
                    user=user,
                    area=area,
                    title=title,
                    price=price,
                    address=address,
                    room_count=room_count,
                    acreage=acreage,
                    unit=unit,
                    capacity=capacity,
                    beds=beds,
                    deposit=deposit,
                    min_days=min_days,
                    max_days=max_days,
                )
                house.facility.add(*[i for i in facility_list])
                # for fac in facility_list:
                #     fac = Facility.objects.get(id=fac.id)
                #     house.facilities.add(*[int(fac)])

            except Exception as e:
                logging.error(e)

                return JsonResponse({'errmsg': '发布房源失败',
                                          'errno': 4302, })

        house = House.objects.order_by('-update_time').filter(user=user)[0]
        return JsonResponse({'errno': 0,
                                  'errmsg': '获取成功',
                                  'data': {'house_id': house.id}})


'''上传房源图片'''
class ImageView(View):
    def post(self, request, house_id):

        # FILES属性获取图片数据
        client = Fdfs_client(settings.PASTDFS_PATH)
        data = request.FILES.get('house_image')
        ret = client.upload_by_buffer(data.read())
        remote = ret['Remote file_id']
        url = settings.FDFS_BASE_URL + remote


        if not house_id:
            return JsonResponse({'errmsg':'未指定房屋','errno':4103,})


        try:
            house = House.objects.get(id = house_id)
        except Exception as e:
            return JsonResponse({'errmsg':'没有找到对应的房屋',
                                  'errno':4002,})
        try:
            if not house.index_image_url:
                house.index_image_url = remote
                house.save()
            else:
                HouseImage.objects.create(
                    house_id = house.id,url = remote)

        except Exception as e:
            return JsonResponse({'errmsg':'保存图片失败',
                                  'errno':4302,})

        return JsonResponse({'errno':0,
                                  'errmsg':'ok',
                                  'data':{'url':url}})


'''我得房源列表'''
class MyHouseView(LoginRequiredMixin,View):
    '''我的房源'''
    def get(self,request):
        user = request.user
        try:
            houses = House.objects.filter(user=user)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errmsg':'查找房源错误',
                                        'errno':4001,})

        if not houses:
            return JsonResponse({'errmsg':"你还没有房源，请先添加",
                                        'errno':4002,})

        house_list = []
        for house in houses:
            house_list.append({
                'address':house.address,
                'area_name':house.area.name,
                'ctime':house.create_time.strftime('%Y-%m-%d'),
                'house_id':house.id,
                'img_url':house.index_image_url,
                'order_count':house.order_count,
                'price':house.price,
                'room_count':house.room_count,
                'title':house.title,
                'user_avatar':house.user.avatar.url
            })

        return JsonResponse({'errmsg':'获取成功',
                                  'errno':'0',
                                  'data':house_list})


'''首页房源推荐'''
class HouseIndexView(View):
    def get(self,request):
        houses = House.objects.all().order_by('-create_time')[:5]
        data  = []
        for house in houses:
            data.append({
                'house_id':house.id,
                'img_url': settings.FDFS_BASE_URL + house.index_image_url,
                'title':house.title
            })
        return JsonResponse({'errmsg':'获取成功','errno':0,'data':data})

#
# '''房屋数据搜索'''
# class HomeSerView(View):
#     '''房屋数据搜索'''
#


'''房屋详情页面'''
class DetailView(View):
    def get(self, request, house_id):
        try:
            house = House.objects.get(id=house_id)
            orders = Order.objects.filter(house_id=house.id)
            imgs = HouseImage.objects.filter(house_id=house.id)

        except Exception as e:
            return JsonResponse({'errmsg': '获取房源失败',
                                      'errno': 4002, })

        img_url_list = []
        for img in imgs:
            img_url_list.append(img.url)

        comments = []
        for order in orders:
            comments.append({'comment': order.comment,
                             'ctime': order.create_time,
                             'user_name': order.user.username})

        # 多对多关系
        facility_list = []
        for fac in house.facility.all():
            facility_list.append(fac.name)

        house_dict = {'acreage': house.acreage,
                      'address': house.address,
                      'beds': house.beds,
                      'capacity': house.capacity,
                      'comments': comments,
                      'deposit': house.deposit,

                      'facilities': facility_list,

                      'hid': house.id,
                      'img_url': img_url_list,
                      'max_days': house.max_days,
                      'min_days': house.min_days,
                      'price': house.price,
                      'room_count': house.room_count,
                      'title': house.title,
                      'unit': house.unit,
                      'user_avatar': house.user.avatar.url,
                      'user_id': house.user.id,
                      'user_name': house.user.real_name
                      }

        data = {'house': house_dict,
                'user_id': house.user.id}

        return JsonResponse({'data': data,
                                  'errmsg': '获取成功',
                                  'errno': '0'})




